<script setup lang="ts">
import { useOperate } from '@/stores/operate' // 操作仓库
import { useDictStore } from '@/stores/Dict' // 字典仓库
import HyForm from '@/common/hy-form/src/HyForm.vue'
import { IFormItem } from '@/common/hy-form'
import { detailRole, getAllUser } from '@/service/api/sys/role/role'
import { getMenuTreeStrueture } from '@/service/api/sys/menu/menu'
import {
  addUser,
  delUser,
  delUsers,
  editUser,
  editUserPassword
} from '@/service/api/sys/user/user'
import { ElMessageBox } from 'element-plus'

const DictStore = useDictStore()
const operate = useOperate()
const Router = useRouter()
const RegionOptions = DictStore.$state.region // 所有行政区
const politicalOptions = DictStore.$state.political // 所有政治面貌
const partyOrgUser = DictStore.$state.partyOrgUser // 所有用户管理-按党组织分组查询
const partyCategory = DictStore.$state.partyCategory // 所有党员类别
const roleList = ref<Array<any>>([]) // 所有角色列表
const genderOptions = [
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 2
  }
] // 性别
const roleShowForm = ref({
  codeList: [], // 当前角色的权限
  menuTree: [], // 所有权限
  props: {
    value: 'code',
    label: 'name',
    children: 'childrenList',
    disabled: () => true
  }, // 菜单结构展示字段
  treeNode: null
}) // 权限展示列表
const treeNode = ref<any>(null) // 权限展示实例
const itemStyle = {
  marginRight: '15px',
  display: 'flex',
  flexDirection: 'column'
} // 基础样式

// 切换用户信息模块与使用权限模块
const infoOrRole = ref<Boolean>(false)

// 当前表单类型: 查询 新增 编辑 修改密码 删除 批量删除
const formType = operate.$state.type

// 当前的操作类名
const title = operate.$state.typeObj[formType]

// 是否禁用 --- 查询 新增 编辑
const isDisabled = computed(() => {
  return formType === 1
})

// 基础信息
const formBase = ref<Array<IFormItem>>([
  {
    type: 'input',
    field: 'account',
    label: '账号',
    otherOptions: {
      disabled: true
    }
  },
  {
    type: 'password',
    field: 'password',
    label: '密码',
    otherOptions: {
      disabled: true
    }
  },
  {
    type: 'input',
    field: 'name',
    label: '姓名',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'cascade',
    field: 'regionId',
    label: '行政区',
    options: RegionOptions,
    optionsKey: 'name',
    optionsValue: 'id',
    optionsChildren: 'childrenList',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'input',
    field: 'position',
    label: '职务',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'input',
    field: 'age',
    label: '年龄',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'select',
    field: 'gender',
    label: '性别',
    options: genderOptions,
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'input',
    field: 'phone',
    label: '联系方式',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'select',
    field: 'politicalOutlookId',
    label: '政治面貌',
    options: politicalOptions,
    optionsKey: 'name',
    optionsValue: 'id',
    otherOptions: {
      disabled: isDisabled
    }
  }
])

// 党员信息
const formParty = ref<Array<IFormItem>>([
  {
    type: 'cascade',
    field: 'partyOrgId',
    options: partyOrgUser,
    label: '所属党组织',
    optionsKey: 'name',
    optionsValue: 'id',
    optionsChildren: 'childrenList',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'select',
    label: '党员类别',
    field: 'partyMemberTypeId',
    options: partyCategory,
    optionsKey: 'name',
    optionsValue: 'id',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'datePicker',
    label: '入党时间',
    field: 'joinPartyTime',
    otherOptions: {
      disabled: isDisabled
    }
  },
  {
    type: 'datePicker',
    label: '转正时间',
    field: 'becomeFullTime',
    otherOptions: {
      disabled: isDisabled
    }
  }
])

// 使用权限
const formRole = ref<Array<IFormItem>>([
  {
    type: 'select',
    label: '选择角色',
    field: 'roleId',
    options: roleList.value,
    optionsKey: 'name',
    optionsValue: 'id',
    otherOptions: {
      disabled: isDisabled
    }
  }
])

// 修改密码
const formPassword = ref<Array<IFormItem>>([
  {
    type: 'password',
    label: '新密码',
    field: 'password'
  },
  {
    type: 'password',
    label: '旧密码',
    field: 'oldPassword',
    otherOptions: {
      disabled: true
    }
  }
])

// 表单内容
const form = ref<any>(operate.$state.form)

// 当角色改变 => 更新权限
watch(
  () => form.value.roleId,
  async (value) => {
    const trueArr = [1, 2, 3]
    if (trueArr.includes(formType)) {
      const res = await detailRole({ id: value })
      roleShowForm.value.codeList = res.data ? res.data.codeList : []
      treeNode.value.setCheckedNodes(roleShowForm.value.codeList)
    }
  },
  { immediate: true }
)

// 更新数据
const updateForm = (value: any) => {
  form.value = value
}

// 获取所有角色
const getInfoList = async () => {
  const res = await getAllUser({})
  roleList.value.push(
    ...[
      {
        id: -1,
        name: '请选择'
      },
      ...res.data
    ]
  )
  console.log(roleList.value)
}

// 获取菜单列表
const getMenuTree = () => {
  getMenuTreeStrueture()
    .then((res) => {
      roleShowForm.value.menuTree = res.data
    })
    .catch((err) => {
      console.log(err)
    })
}

// 保存用户
const saveUser = async () => {
  ElMessageBox.confirm(`确认${title}?`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        switch (formType) {
          case 2:
            // 新增
            await addUser(form.value)
            break
          case 3:
            await editUser(form.value)
            // 编辑
            break
          case 4:
            // 修改密码
            await editUserPassword(form.value)
            break
          case 5:
            await delUser(form.value)
            // 删除
            break
          case 6:
            await delUsers(form.value)
            break
          default:
            ElMessage({
              type: 'warning',
              message: `${title}错误!`
            })
            // 其他
            break
        }
        ElMessage({
          type: 'success',
          message: `${title}成功, 稍后返回!`
        })
        setTimeout(() => {
          Router.back()
        }, 1000)
      } catch {
        ElMessage({
          type: 'error',
          message: `${title}失败, 请重试!`
        })
      }
    })
    .catch(() => {})
}

onMounted(() => {
  getMenuTree()
  getInfoList()
})
</script>

<template>
  <div>
    <div class="flex flex-col">
      <!-- 修改密码 -->
      <div v-if="formType === 4">
        <hy-form
          :model-value="form"
          :formItems="formPassword"
          labelWidth="auto"
          :colLayout="{ xl: 1 }"
          :itemStyle="itemStyle"
          @update:modelValue="updateForm"
        />
      </div>
      <!-- 删除/批量删除 -->
      <div
        v-else-if="formType === 5 || formType === 6"
        class="w-[300px] text-center text-sm"
      >
        删除后系统内和该用户相关数据将一并清空, 是否确定删除？
      </div>
      <div v-else class="h-[600px] w-[756px] overflow-y-auto">
        <el-switch
          v-model="infoOrRole"
          class="flex w-full justify-center border-0"
          style="--el-switch-on-color: #5e9db4; --el-switch-off-color: #5e9db4"
          active-text="使用权限"
          inactive-text="用户信息"
        />
        <!--第一个板块用户信息-->
        <div v-show="!infoOrRole">
          <div
            class="border-b border-[--auxiliary] py-[8px] text-center text-xs text-[--auxiliary]"
          >
            基本信息
          </div>
          <hy-form
            :model-value="form"
            :formItems="formBase"
            labelWidth="auto"
            :itemStyle="itemStyle"
            @update:modelValue="updateForm"
          />
          <div
            class="border-b border-[--auxiliary] py-[8px] text-center text-xs text-[--auxiliary]"
          >
            党员信息
          </div>
          <hy-form
            :model-value="form"
            :formItems="formParty"
            labelWidth="auto"
            :itemStyle="itemStyle"
            @update:modelValue="updateForm"
          />
        </div>
        <!--第二个板块权限信息-->
        <div v-show="infoOrRole" class="flex flex-col">
          <hy-form
            :model-value="form"
            :formItems="formRole"
            labelWidth="auto"
            :itemStyle="itemStyle"
            @update:modelValue="updateForm"
          />
          <el-tree
            :data="roleShowForm.menuTree"
            show-checkbox
            accordion
            node-key="code"
            :default-checked-keys="roleShowForm.codeList"
            :props="roleShowForm.props"
            class="roleOperation w-full overflow-auto"
            disabled
            ref="treeNode"
          />
        </div>
      </div>
      <div class="mt-7 flex justify-center">
        <el-button type="primary" class="button_default" @click="Router.back()"
          >关闭</el-button
        >
        <el-button
          v-if="!isDisabled"
          :type="formType === 5 || formType === 6 ? 'danger' : 'primary'"
          :class="
            formType === 5 || formType === 6
              ? 'button_delete'
              : 'button_function'
          "
          @click="saveUser"
          >{{ formType === 5 || formType === 6 ? '删除' : '保存' }}</el-button
        >
      </div>
    </div>
  </div>
</template>

<style scoped>
.title {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #5e9db4;
}

.title_active {
  font-weight: bold;
  color: #ffffff;
}

/*设置进度条的高度*/
:deep(.el-switch__core) {
  width: 100px;
  height: 3px;
}

/*设置滑块*/
:deep(.el-switch__core .el-switch__action) {
  width: 12px;
  height: 12px;
  background: #5e9db4;
}

:deep(.el-switch__label) {
  color: #5e9db4;
  font-weight: 100;
}

:deep(.is-active) {
  color: white;
  font-weight: bold;
}
</style>
